<template>
  <div>
    <div class="ccui-navigation">
      <el-button
          size="mini"
          type="primary-icon-medium"
          icon="icon-ccui-return"
          @click="handleBack"
      >返回
      </el-button
      >
      <div class="ccui-navigation-divider"/>
      <!-- 面包屑 -->
      <el-breadcrumb
          class="ccui-navigation-crumbs-container"
          separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
            :to="{ path: $store.getters.getBreadcrumb('level1').path }"
        >{{ $store.getters.getBreadcrumb("level1").name }}
        </el-breadcrumb-item
        >
        <el-breadcrumb-item
            :to="{
            path: '/inventoryManagement/storeManagement/storeManagementList'
          }"
        >库存管理(财务)
        </el-breadcrumb-item
        >
        <el-breadcrumb-item
            :to="{
            path: '/inventoryManagement/storeManagement/storeManagementList'
          }"
        >仓库管理
        </el-breadcrumb-item
        >
        <el-breadcrumb-item
            :to="{
            path: '/inventoryManagement/storeManagement/storeManagementList'
          }"
        >仓库维护
        </el-breadcrumb-item
        >
        <el-breadcrumb-item>
          <span>{{ titleType }}</span>
          <span class="ccui-curr-crumb ccui-ml-10">
            {{ titleName }}
          </span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-group-title title="仓库维护">
          <template slot="groupTitle">
            <el-form
                :model="form"
                :rules="rules"
                ref="form"
                label-width="160px"
                class="ccui-form"
            >
              <!--填报单位、库存地点-->
              <el-row>
                <el-col :span="12">
                  <el-form-item label="填报单位：" prop="reportInOrgName">
                    <el-select
                        v-model="form.reportInOrgId"
                        class="ccui-form-longInput"
                        placeholder="请选择填报单位"
                        @change="handleReportInOrg"
                        :disabled="
                        $route.query.isReference &&
                        $route.query.isReference == 1
                      "
                    >
                      <el-option
                          v-for="item in reportInOrg"
                          :key="item.orgId"
                          :label="item.name"
                          :value="item.orgId"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="库存地点：" prop="warehousePlace">
                    <el-input
                        v-model="form.warehousePlace"
                        class="ccui-form-longInput text-limit"
                        placeholder="请输入库存地点"
                        maxlength="500"
                        show-word-limit
                        :disabled="
                        $route.query.isReference &&
                        $route.query.isReference == 1
                      "
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <!--项目名称、核算组织-->
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目名称：" prop="projectName">
                    <el-input v-model="form.projectName" disabled/>
                    <el-button
                        plain
                        type="single-number"
                        style="margin-left: 10px"
                        @click="handleShowProjectNameDialog"
                    >选择
                    </el-button
                    >
                    <el-button
                        plain
                        type="single-number"
                        style="margin-left: 10px"
                        @click="handleProjectName"
                    >清空
                    </el-button
                    >
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="核算组织：" prop="accountingOrgan">
                    <el-input v-model="form.accountingOrgan" disabled/>
                    <el-button
                        plain
                        type="single-number"
                        style="margin-left: 10px"
                        @click="handleShowAccountingOrganDialog"
                    >选择
                    </el-button
                    >
                    <el-button
                        plain
                        type="single-number"
                        style="margin-left: 10px"
                        @click="handleAccountingOrgan"
                    >清空
                    </el-button
                    >
                  </el-form-item>
                </el-col>
              </el-row>

              <!--仓库编号、仓库名称-->
              <el-row>
                <el-col :span="12">
                  <el-form-item label="仓库编号：" prop="warehouseCode">
                    <el-input
                        v-model="form.warehouseCode"
                        class="ccui-form-longInput"
                        placeholder=""
                        disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="仓库名称：" prop="warehouseName">
                    <el-input
                        v-model="form.warehouseName"
                        class="ccui-form-longInput text-limit"
                        placeholder="请输入仓库名称"
                        maxlength="300"
                        show-word-limit
                        :disabled="
                        $route.query.isReference &&
                        $route.query.isReference == 1
                      "
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <!--本位币币种、计税方式-->
              <el-row>
                <el-col :span="12">
                  <el-form-item label="本位币币种：" prop="standardMoney">
                    <el-input
                        v-model="form.standardMoney"
                        disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计税方式：" prop="valoremMethod">
                    <el-input
                        v-model="form.valoremMethod"
                        disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <!--联系电话、编制人-->
              <el-row>
                <el-col :span="12">
                  <el-form-item label="联系电话：" prop="warehousePhone">
                    <el-input
                        v-model="form.warehousePhone"
                        class="ccui-form-longInput"
                        placeholder="请输入联系电话"
                        show-word-limit
                        maxlength="11"
                        oninput="this.value=this.value.replace(/[^\d.]/g,'')"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="编制人：">
                    <el-input
                        v-model="form.compilePeople"
                        class="ccui-form-longInput"
                        placeholder="请输入编制人"
                        disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <!--编制时间-->
              <el-row>
                <el-col :span="12">
                  <el-form-item label="编制时间：">
                    <el-input
                        v-model="form.compileDate"
                        class="ccui-form-longInput"
                        disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <!--仓库描述-->
              <el-row>
                <el-col :span="24">
                  <el-form-item
                      label="仓库描述："
                      :title="form.warehouseDescribe"
                  >
                    <el-input
                        type="textarea"
                        :rows="5"
                        placeholder="请输入仓库描述"
                        v-model="form.warehouseDescribe"
                        maxlength="1000"
                        show-word-limit
                        class="remarkClass"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </template>
        </el-group-title>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button type="bottom" icon="icon-ccui-save" @click="handleSave()"
          >保存并校验
          </el-button
          >
        </li>
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
          >返回
          </el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
    <!-- 项目名称弹框 -->
    <chooseSupplier
        ref="projectNameBakVisibleDialog"
        :supplierData="projectObj"
        @selectPartyB="selectProjectName"
    />

    <!-- 核算组织弹框 -->
    <chooseSupplier
        ref="accountingOrganBakVisibleDialog"
        :supplierData="accountingOrganObj"
        @selectPartyB="selectAccountingOrgan"
    />
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import {getStoreAdd, getStoreDetail, getStoreEditor, qryProjectDataAll} from "../api";
import {getUserInfoA, getListUserPartJobComInfo, listAccountingUnitByBO} from "@/basa/api";
import publicComponent from "@/basa/components/public";

export default {
  name: "storeManagementAdd",
  components: {
    chooseSupplier: publicComponent.singleSupplier,
  },
  data() {
    return {
      form: {
        reportInOrgName: "",
        reportInOrgId: "",
        warehousePlace: "",
        warehouseCode: "",
        warehouseName: "",
        warehousePhone: "",
        compilePeople: "",
        compileDate: "",
        warehouseDescribe: "",
        projectCode: "",
        projectName: "",
        accountingOrganCode: "",
        accountingOrgan: "",
        standardMoneyCode: "156",
        standardMoney: "人民币",
        valoremMethodCode: "1",
        valoremMethod: "一般计税",
      },
      projectObj: {
        title: "项目名称查询",
        tableHeadOptions: [
          {
            prop: "zprojname",
            label: "项目中文名称",
            width: "170",
            type: "input",
            showSearch: true,
          },
          {
            prop: "zproOrgName",
            label: "项目机构",
            width: "120",
            type: "input",
          },
          {
            prop: "zproject",
            label: "项目编码",
            width: "130",
            type: "input",
          },
          {
            prop: "zprojtypeName",
            label: "项目类型",
            width: "130",
            type: "input",
          },
          {prop: "projectAllName", label: "项目所在地", width: "130", type: "input"},
          {
            prop: "zprojyear",
            label: "项目年份",
            width: "80",
            type: "input",
          },
        ],
        tableData: [],
        recordsTotal: 0,
        formDate: {
          fillOrg: "",
          contractOrderOrg: "",
          pageNo: 1,
          pageSize: 10
        }
      },
      accountingOrganObj: {
        title: "核算组织查询",
        tableHeadOptions: [
          {prop: "chsName", label: "核算组织", width: "130", type: "input",showSearch: true,},
        ],
        tableData: [],
        recordsTotal: 0,
        formDate: {
          pageNo: 1,
          pageSize: 10
        }
      },
      smpProjectReqBO: {},
      reportInOrg: [],
      titleType: "",
      titleName: "",
      rules: {
        warehouseCode: [
          {required: true, message: "请输入仓库编号", trigger: "blur"}
        ],
        warehouseName: [
          {required: true, message: "请输入仓库名称", trigger: "blur"}
        ],
        warehousePlace: [
          {required: true, message: "请输入库存地点", trigger: "blur"}
        ],
        warehousePhone: [
          {required: true, message: "请输入联系电话", trigger: "blur"}
        ],
        reportInOrgName: [
          {required: true, message: "请输入填报单位", trigger: "blur"}
        ],
        projectName: [
          {required: true, message: "请选择项目", trigger: "change"}
        ],
        accountingOrgan: [
          {required: true, message: "请选择核算组织", trigger: "change"}
        ],
        standardMoney:[
          {required: true, message: "请选择核算组织",trigger:"blur"},
        ],
        valoremMethod:[
          {required: true, message: "请选择项目",trigger:"blur"},
        ],
      },
    };
  },
  props: {},
  watch: {
    "form.warehouseName": {
      handler(val) {
        this.titleName = val;
      },
      deep: true
    }
  },
  created() {
    this.titleType = this.$route.query.newAdd == 1 ? "新增" : "编辑";
    if (this.$route.query.id) {
      let id = this.$route.query.id;
      this.getStoreDetail({id: id});
    }
  },
  mounted() {
    this.form.compileDate = this.getDate();
    if (this.titleType == "新增") {
      getUserInfoA({}).then(res => {
        if (res.data.code == 0) {
          this.form.compilePeople = res.data.data.userInfo.name;
          let openIds = [res.data.data.userInfo.openId];
          getListUserPartJobComInfo({openIds: openIds}).then(res => {
            if (res.data.code == 0) {
              this.reportInOrg = res.data.data[openIds];
              this.form.reportInOrgName = res.data.data[openIds][0].name;
              this.form.reportInOrgId = res.data.data[openIds][0].orgId;
            }
          });
        }
      });
    } else {
      getUserInfoA({}).then(res => {
        if (res.data.code == 0) {
          this.form.compilePeople = res.data.data.userInfo.name;
          let openIds = [res.data.data.userInfo.openId];
          getListUserPartJobComInfo({openIds: openIds}).then(res => {
            if (res.data.code == 0) {
              this.reportInOrg = res.data.data[openIds];
            }
          });
        }
      });
    }
  },
  methods: {
    // 获取时间方法
    getDate() {
      let date = new Date();
      let seperator1 = "-";
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },
    // 选择填报单位
    handleReportInOrg(data) {
      this.form.reportInOrgName = this.reportInOrg.filter(item => {
        return item.orgId === data;
      })[0].name;
    },
    // 返回
    handleBack() {
      this.$router.go(-1);
    },
    // 保存
    handleSave() {
      if (this.titleType == "新增") {
        this.getStoreAdd();
      } else {
        this.getStoreEditor();
      }
    },
    //查详情
    getStoreDetail(data) {
      getStoreDetail(data).then(res => {
        if (res.data.code == 0) {
          this.form = res.data.data;
          if (this.form.compileDate) {
            this.form.compileDate = this.form.compileDate.substring(0, 10);
          } else {
            this.form.compileDate = this.getDate();
          }
        }
      });
    },
    //新增
    getStoreAdd() {
      getStoreAdd(this.form).then(res => {
        if (res.data.code == 0) {
          this.$router.push({
            path: "/inventoryManagement/storeManagement/storeManagementList"
          });
        }
        this.$message.success(res.data.message);
      });
    },
    //编辑
    getStoreEditor() {
      getStoreEditor(this.form).then(res => {
        this.$message.success(res.data.message);
        if (res.data.code == 0) {
          this.$router.push({
            path: "/inventoryManagement/storeManagement/storeManagementList"
          });
        }
      });
    },


    // 财务云对接

    // 项目名称显示
    handleShowProjectNameDialog() {
      this.$refs.projectNameBakVisibleDialog.visible = true;
      this.getProjectNameData(
          this.form.reportInOrgId,
          this.form.partyAId,
          this.projectObj.formDate
      );
    },
    // 取消项目名称
    handleProjectName() {
      this.form.projectName = ""; // 项目名称
      this.form.projectCode = null; // 项目编码
      this.smpProjectReqBO = {};
    },
    // 项目名称设置 start

    // 获取项目名称数据
    getProjectNameData(
        fillOrg,
        // contractOrderOrg,
        defaultParams = this.projectObj.formDate
    ) {
      const data = Object.assign(defaultParams, { fillOrg });
      // const data = defaultParams;
      qryProjectDataAll(data).then(res => {
        const tableData = res.data.data.rows;
        tableData.forEach(item => {
          item.projectAllName =
              item.zzcountryName + item.provinceName + item.zprojlocName;
        });
        this.projectObj.tableData = tableData;
        this.projectObj.recordsTotal = res.data.data.recordsTotal;
      });
    },

    // 项目名称
    selectProjectName(val) {
      console.log("选中的项目名称", val);
      if (val.status === "confirm") {
        const {
          confirmSelect,
          confirmSelect: {
            zprojtypeName,
            zprojname,
            zproject,
            z2ndorg,
            zapproval,
            zapvldate,
            zcpbc,
            zfindate,
            zhereinafter,
            zstartdate,
            zproOrg,
            zprojectup,
            zprojename,
            zprojlocName,
            zprojtype,
            zprojyear,
            zstate,
            zzcountryName,
            zzcountry,
            provinceCode,
            provinceName,
            zprojloc,
            zproOrgName,
            zacorgId,
            zacorgno
          }
        } = val;

        const str = this.getType(confirmSelect);

        console.log("str:", str, "val:", val);

        if (str === "Object") {
          this.resetProjectNameParams("projectObj");
          this.form.projectCode = zproject;
          this.form.projectName = zprojname;
          this.smpProjectReqBO.projectType = zprojtypeName; // 项目类型
          this.smpProjectReqBO.projectTypeCode = zprojtype; // 项目类型编码
          this.smpProjectReqBO.projectCode = zproject; // 项目编号
          this.smpProjectReqBO.projectSuperiorCode = zprojectup; // 项目上级编码
          this.smpProjectReqBO.projectName = zprojname; // 项目名称
          this.smpProjectReqBO.projectForeignName = zprojename; // 项目外文名称
          this.smpProjectReqBO.projectAbbreviation = zhereinafter; // 项目简称
          this.smpProjectReqBO.countryCode = zzcountry; // 国家编码
          this.smpProjectReqBO.country = zzcountryName; // 国家/地区
          this.smpProjectReqBO.provinceCode = provinceCode; // 省编码
          this.smpProjectReqBO.province = provinceName; // 省
          this.smpProjectReqBO.cityCode = zprojloc; // 市编码
          this.smpProjectReqBO.city = zprojlocName; // 市
          this.smpProjectReqBO.projectLocation = zprojlocName; // 项目所在地
          this.smpProjectReqBO.businessTypeZj = zcpbc; // 中交行业业务类型
          this.smpProjectReqBO.approvalNo = zapproval; // 项目批复/决议号
          this.smpProjectReqBO.approvalDate = zapvldate
              ? Date.parse(zapvldate)
              : ""; // 项目批复/决议时间
          this.smpProjectReqBO.projectOrgan = zproOrgName; // 项目机构名称
          this.smpProjectReqBO.projectOrganId = zproOrg; // 项目机构
          this.smpProjectReqBO.projectYear = zprojyear; // 项目年份
          this.smpProjectReqBO.planStartDate = zstartdate
              ? Date.parse(zstartdate)
              : ""; // 项目计划开始日期
          this.smpProjectReqBO.planEndDate = zfindate
              ? Date.parse(zfindate)
              : ""; // 项目计划完成日期
          this.smpProjectReqBO.secondLevelOrgan = z2ndorg; // 所属二级单位
          this.smpProjectReqBO.state = zstate; // 状态
          this.smpProjectReqBO.accountingOrganId = zacorgId; // 核算组织id
          this.smpProjectReqBO.accountingOrganCode = zacorgno; // 核算组织编码
        }
        this.selectProjectNameReset();
      } else {
        this[this.getSelectProjectNameStrategy[val.status]](val);
        if (["closeReset"].includes(val.status)) return; // 点击叉号只清空数据，不调接口
        this.getProjectNameData(
            this.form.reportInOrgId,
            // this.form.partyAId,
            this.projectObj.formDate
        );
      }
    },

    // 项目查询
    selectProjectNameSearch(val) {
      this.projectObj.formDate = val.formDate;
      this.projectObj.formDate.pageNo = 1;
    },

    // 当前页条数
    selectProjectNamePageSize(val) {
      this.projectObj.formDate.pageSize = val.pageSize;
    },

    // 页码
    selectProjectNamePageNo(val) {
      this.projectObj.formDate.pageNo = val.pageNo;
    },

    // 项目名称重置
    selectProjectNameReset(val) {
      this.projectObj.formDate = {
        fillOrg: "",
        contractOrderOrg: "",
        pageNo: 1,
        pageSize: 10
      };
    },

    // 重置项目名称参数
    resetProjectNameParams(str) {
      this.projectObj.formDate = {
        ...this.projectObj.formDate,
        pageNo: 1,
        pageSize: 10
      };
    },

    // 项目名称设置 end


    // 核算组织显示
    handleShowAccountingOrganDialog() {
      this.$refs.accountingOrganBakVisibleDialog.visible = true;
      this.getAccountingOrganData(
          this.accountingOrganObj.formDate
      );
    },
    // 取消核算组织
    handleAccountingOrgan() {
      this.form.accountingOrgan = ""; // 核算组织名称
      this.form.accountingOrganCode = null; // 核算组织编码
    },
    // 核算组织设置 start

    // 获取核算组织数据
    getAccountingOrganData(
        defaultParams = this.accountingOrganObj.formDate
    ) {
      // const data = Object.assign(defaultParams, { fillOrg,contractOrderOrg });
      const data = defaultParams;
      listAccountingUnitByBO(data).then(res => {
        const tableData = res.data.data.rows;
        this.accountingOrganObj.tableData = tableData;
        this.accountingOrganObj.recordsTotal = res.data.data.recordsTotal;
      });
    },

    // 核算组织
    selectAccountingOrgan(val) {
      if (val.status === "confirm") {
        const {
          confirmSelect,
          confirmSelect: {
            chsName,
            acOrgCode,
          }
        } = val;

        const str = this.getType(confirmSelect);

        console.log("str:", str, "val:", val);

        if (str === "Object") {
          this.resetAccountingOrganParams("accountingOrganObj");
          this.form.accountingOrganCode = acOrgCode;
          this.form.accountingOrgan = chsName;
        }
        this.selectAccountingOrganReset();
      } else {
        this[this.getSelectAccountingOrganStrategy[val.status]](val);
        if (["closeReset"].includes(val.status)) return; // 点击叉号只清空数据，不调接口
        this.getAccountingOrganData(
            this.accountingOrganObj.formDate
        );
      }
    },

    // 核算组织查询
    selectAccountingOrganSearch(val) {
      this.accountingOrganObj.formDate = val.formDate;
      this.accountingOrganObj.formDate.pageNo = 1;
    },

    // 当前页条数
    selectAccountingOrganPageSize(val) {
      this.accountingOrganObj.formDate.pageSize = val.pageSize;
    },

    // 页码
    selectAccountingOrganPageNo(val) {
      this.accountingOrganObj.formDate.pageNo = val.pageNo;
    },

    // 核算组织重置
    selectAccountingOrganReset(val) {
      this.accountingOrganObj.formDate = {
        pageNo: 1,
        pageSize: 10
      };
    },

    // 重置核算组织参数
    resetAccountingOrganParams(str) {
      this.accountingOrganObj.formDate = {
        ...this.accountingOrganObj.formDate,
        pageNo: 1,
        pageSize: 10
      };
    },

    // 核算组织设置 end

    // 工具类
    getType(obj) {
      return Object.prototype.toString
          .call(obj)
          .replace(/^\[object (\S+)\]$/, "$1");
    },
  },
  computed: {
    ...mapGetters([
      "getSelectProjectNameStrategy", // 项目名称操作
      "getSelectAccountingOrganStrategy" // 核算组织操作
    ])
  },
};
</script>

<style scoped lang="scss">
/deep/ .el-input {
  width: 260px;
}

/deep/ .el-button--single-number {
  width: 46px;
  margin-left: 10px;
  padding: 0 9px;
}

/deep/ .ccui-pre-form-item {
  .el-form-item__label {
    line-height: 16px;
  }
}

.remarkClass {
  width: calc(50% + 350px);
}

.text-limit{
  /deep/.el-input__inner {
    padding-right: 50px;
  }
}

</style>
